package com.hyp.pay.UI.Home.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.baidu.tts.auth.AuthInfo;
import com.baidu.tts.client.SpeechError;
import com.baidu.tts.client.SpeechSynthesizeBag;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.baidu.tts.client.TtsMode;
import com.hyp.pay.R;
import com.hyp.pay.UI.Home.presenter.PicturePresenter;
import com.hyp.pay.UI.Home.presenter.contract.EditContract;
import com.hyp.pay.UI.Home.presenter.contract.PictureContract;
import com.hyp.pay.UI.Zxing.activity.TestScanActivity;
import com.hyp.pay.base.BaseActivity;
import com.hyp.pay.base.SimpleActivity;
import com.hyp.pay.camera.CameraHelper2;
import com.hyp.pay.device.N900Device;
import com.hyp.pay.device.N900Device2;
import com.hyp.pay.http.Constants;
import com.hyp.pay.http.HyqApis;
import com.hyp.pay.model.EventDevice;
import com.hyp.pay.model.FindRecharge;
import com.hyp.pay.model.UplodIdcard;
import com.hyp.pay.model.UserJson;
import com.hyp.pay.network.NetBroadcastReceiver;
import com.hyp.pay.network.NetEvent;
import com.hyp.pay.utils.FileCacheUtils;
import com.hyp.pay.utils.NetWorkUtils;
import com.hyp.pay.utils.SPUtil;
import com.hyp.pay.utils.SystemUtil;
import com.hyp.pay.weight.CustomPopupWindow;
import com.hyp.pay.weight.ErrorLayout;
import com.hyp.pay.weight.ProgressDialog;
import com.newland.mtype.module.common.printer.Printer;
import com.newland.mtype.module.common.printer.PrinterResult;
import com.newland.mtype.module.common.printer.PrinterStatus;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;


import static com.hyp.pay.R.id.webView;

public class HomeActivity extends BaseActivity<PicturePresenter> implements SpeechSynthesizerListener, View.OnClickListener,
        NetEvent, PictureContract.View, CustomPopupWindow.OnItemClickListener {

    private static N900Device2 n900Device2;

    /**
     * 网络状态
     */
    private int netMobile;

    /**
     * 这里保存一个值用来判断网络是否经历了由断开到连接
     */
    private boolean isNetChanges;

    /**
     * 监控网络的广播
     */
    private NetBroadcastReceiver netBroadcastReceiver;


    private String mIndexUrl = HyqApis.HOST + "app_index.html";
    private ProgressDialog mDialog;

    //   百度
    private SpeechSynthesizer mSpeechSynthesizer;
    private String mSampleDirPath;
    private static final String SAMPLE_DIR_NAME = "baiduTTS";
    private static final String SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female.dat";
    private static final String SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male.dat";
    private static final String TEXT_MODEL_NAME = "bd_etts_text.dat";
    private static final String LICENSE_FILE_NAME = "temp_license";
    private static final String ENGLISH_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female_en.dat";
    private static final String ENGLISH_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male_en.dat";
    private static final String ENGLISH_TEXT_MODEL_NAME = "bd_etts_text_en.dat";

    private static final int PRINT = 0;
    private static final int UI_CHANGE_INPUT_TEXT_SELECTION = 1;
    private static final int UI_CHANGE_SYNTHES_TEXT_SELECTION = 2;
    private static final String TAG = "MainActivity";

    private String urlPath;
    private CustomPopupWindow mPop;
    private static final int PHOTOS_SUCCESS = 200;
    private static final int PHOTOS_FAILURE = 500;
    public final static int ALBUM_REQUEST_CODE = 1;
    public final static int CROP_REQUEST = 2;
    public final static int CAMERA_REQUEST_CODE = 3;
    public static String SAVED_IMAGE_DIR_PATH =
            Environment.getExternalStorageDirectory().getPath()
                    + "/hyp/camera/";// 拍照路径
    String cameraPath;
    private int PHOTO_REQUEST_TAKEPHOTO = 0x2;
    private String nextUrl;
    @BindView(webView)
    WebView mWebView;
    @BindView(R.id.image)
    ImageView mImage;
    @BindView(R.id.error_layout)
    ErrorLayout mErrorLayout;


    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }


    @Override
    protected int getLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
//        if (android.os.Build.DISPLAY.equals("NewLand_N900-7cfaf9357f")) {
//            n900Device = N900Device.getInstance(this);
//            connectDevice2();
//        }

        Intent intent = getIntent();
        if (intent != null) {
            urlPath = intent.getStringExtra(Constants.WEB_VIEW_URL_PATH);
        }
        mDialog = new ProgressDialog(mContext);
        mPop = new CustomPopupWindow(this);
//        mErrorLayout.setState(ErrorLayout.NETWORK_LOADING);
        mErrorLayout.setOnLayoutClickListener(this);
        WebSettings settings = mWebView.getSettings();
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);   //开启 database storage API 功能
        settings.setAppCacheEnabled(true);//开启 Application Caches 功能
        mWebView.addJavascriptInterface(new JsInteraction(), "Oulijun");

//        mWebView.loadUrl(mIndexUrl);
        if (!TextUtils.isEmpty(urlPath)) {
            mWebView.loadUrl(urlPath);
        } else {
            mWebView.loadUrl(mIndexUrl);
        }


        mWebView.setWebViewClient(mWebViewClient);
        initialEnv();
        initialTts();

    }
    // 初始化设备
    public void connectDevice2() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    n900Device2.connectDevice();
                }
            }).start();
        } catch (Exception e) {
//            showMessage("设备连接异常：" + e, Const.MessageTag.ERROR);
        }

    }

    WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            nextUrl = url;
            if (url.contains("https://qr.alipay.com")) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            } else {

                syncCookie2(HomeActivity.this, url);
                mWebView.loadUrl(url);
                Log.i("olj", url);
            }

            if (!isNetChanges) {
                mErrorLayout.setVisibility(View.VISIBLE);
                mErrorLayout.setState(ErrorLayout.NETWORK_ERROR);
            }
//            if (!NetWorkUtils.isConnected(mContext)) {
//                mErrorLayout.setVisibility(View.VISIBLE);
//                mErrorLayout.setState(ErrorLayout.NETWORK_ERROR);
////                if (!url.contains("android_asset")) {
////                    mWebView.loadUrl("file:///android_asset/E404.html?uri="+nextUrl);
////                }
//            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mDialog.show();
            mDialog.setText("加载页面中");
            if (url.contains("app_login.html")) {
                mImage.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mImage.setVisibility(View.GONE);
            mDialog.dismiss();
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//            super.onReceivedError(view, request, error);
            mDialog.dismiss();
            mErrorLayout.setVisibility(View.VISIBLE);
            mErrorLayout.setState(ErrorLayout.NETWORK_ERROR);
//            mWebView.loadUrl("file:///android_asset/E404.html");
        }
    };


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_error_layout:
                mErrorLayout.setState(ErrorLayout.NETWORK_LOADING);
                break;
            case R.id.resfer:
                if (isNetChanges) {
                    Log.i("olj", "1111111111111111111" + nextUrl);
                    mWebView.loadUrl(nextUrl);
                    mErrorLayout.setVisibility(View.GONE);
                } else {
                    mErrorLayout.setVisibility(View.VISIBLE);
                    Toast.makeText(mContext, "当前没网络", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.back:
                if (isNetChanges) {
                    Log.i("olj", "22222222222222222222222222" + nextUrl);
                    mWebView.loadUrl(nextUrl);
                    mErrorLayout.setVisibility(View.GONE);
                } else {
                    mErrorLayout.setVisibility(View.VISIBLE);
                    Toast.makeText(mContext, "当前没网络", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (netBroadcastReceiver == null) {
            netBroadcastReceiver = new NetBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netBroadcastReceiver, filter);
            /**
             * 设置监听
             */
            netBroadcastReceiver.setNetEvent(this);
        }
    }

    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
    }

    private void isNetConnect() {
        switch (netMobile) {
            case 1://wifi
                isNetChanges = true;
//                mtvNet.append("\n当前网络类型:wifi");
                Toast.makeText(mContext, "已连接:wifi", Toast.LENGTH_SHORT).show();
                break;
            case 0://移动数据
                isNetChanges = true;
//                mtvNet.append("\n当前网络类型:移动数据");
                Toast.makeText(mContext, "已连接:移动数据", Toast.LENGTH_SHORT).show();
                break;
            case -1://没有网络
                isNetChanges = false;
                Toast.makeText(mContext, "当前无网络", Toast.LENGTH_SHORT).show();
                break;
        }
        //
//        mtvNet.append("\n" + getStringDate());
        if (isNetChanges) {
//            mtvNet.append("\n当前有网络");
        } else {
//            mtvNet.append("\n当前无网络");
        }
//        mtvNet.append("\n----------------------------------------------------");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (netBroadcastReceiver != null) {
            unregisterReceiver(netBroadcastReceiver);
        }
    }


    /**
     * 获取当前时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    @Override
    public void showUplod(UplodIdcard data) {
        if (data.getCode().equals("200")) {
            Toast.makeText(mContext, "上传成功", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void showFindRecharge(FindRecharge charge) throws JSONException {
        if (charge.getCode().equals("200")){

            String paymentId=charge.getHyqAccountRecharge().getPaymentId();
            String paymentTime=charge.getHyqAccountRecharge().getPaymentTime();
            String moneyFloat=charge.getHyqAccountRecharge().getMoneyfloat();
            String logno=charge.getHyqAccountRecharge().getLogno();
            String shopTradeNo=charge.getHyqAccountRecharge().getShopTradeNo();
            String id=charge.getHyqAccountRecharge().getId();
            SPUtil.seId(id);
            int payMode=charge.getHyqAccountRecharge().getPayMode();
            int paymentStatus=charge.getHyqAccountRecharge().getPaymentStatus();

            String text;
            String pay = "微信";

            if (paymentStatus==0){
                text="待支付";
            }else if (paymentStatus==1){
                text="已支付";
            }else if (paymentStatus==2){
                text="支付失败";
            }else{
                text="异常";
            }

            if (payMode==1){
                pay="微信";
            }else if(payMode==2){
                pay="支付宝";
            }else if (payMode==3){
                pay="百度钱包";
            }else if (payMode==4){
                pay="QQ钱包";
            }else if(payMode==5){
                pay="京东钱包";
            }

            String signImglist=charge.getHyqAccountRecharge().getSignImglist();
//            JSONObject jsonObject = new JSONObject(signImglist);
//            String  SignPayerName=jsonObject.getString("SignPayerName");
//            String  SignDraweeName=jsonObject.getString("SignDraweeName");

            SPUtil.setPaymode(pay);
            SPUtil.setPaymentId(paymentId);
//            SPUtil.setSignPayerName(SignPayerName);
            SPUtil.setPaymentTime(paymentTime);
            SPUtil.setText(text);
            SPUtil.setMoneyFloat(moneyFloat);
            SPUtil.setLogno(logno);
            SPUtil.setShopTradeNo(shopTradeNo);
//            SPUtil.setDraweeName(SignDraweeName);

//              新大陆pos机打印
            if (android.os.Build.DISPLAY.equals("NewLand_N900-7cfaf9357f")) {
                n900Device2 = N900Device2.getInstance(this);
                connectDevice2();
            }
//            衫德pos机打印
//            获取序列号：
//            String serialNum = android.os.Build.SERIAL;
//            if (serialNum)
//

        }

    }

    @Override
    public void showUser(UserJson data) {
        if (data.getCode().equals("200")){

            SPUtil.setUsername(data.getHyqUser().getUsername());


        }

    }
    @Override
    public void showError(String msg) {

    }

    @Override
    public void setOnItemClick(View v) {
        switch (v.getId()) {
            case R.id.id_btn_take_photo:
                Log.i("olj", "拍照");
                Toast.makeText(getApplicationContext(), "拍照", Toast.LENGTH_LONG).show();
                // 指定相机拍摄照片保存地址
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    cameraPath = SAVED_IMAGE_DIR_PATH + System.currentTimeMillis() + ".png";
                    Intent intent = new Intent();
                    // 指定开启系统相机的Action
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    String out_file_path = SAVED_IMAGE_DIR_PATH;
                    File dir = new File(out_file_path);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    } // 把文件地址转换成Uri格式
                    Log.i("olj", cameraPath);
                    Uri uri = Uri.fromFile(new File(cameraPath));
                    // 设置系统相机拍摄照片完成后图片文件的存放地址
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                    mPop.dismiss();
                } else {
                    Toast.makeText(getApplicationContext(), "请确认已经插入SD卡",
                            Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.id_btn_select:
                //调用相册
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, ALBUM_REQUEST_CODE);
                mPop.dismiss();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMERA_REQUEST_CODE) {
                Log.d("olj", "path=" + cameraPath);

                SystemUtil.getBitmap(cameraPath, 200, 200);

                mPresenter.getUploadFilePicture(cameraPath, Integer.parseInt(SPUtil.getUserid()));
            }
        }

        //获取图片路径
        if (requestCode == ALBUM_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            Log.d("olj", "相册path=" + imagePath);
            SystemUtil.getBitmap(imagePath, 200, 200);
            mPresenter.getUploadFilePicture(imagePath, Integer.parseInt(SPUtil.getUserid()));
            c.close();
        }

    }

    public class JsInteraction {
        @JavascriptInterface
        public void startScan(String charge, String userid) {   //提供给js调用的方法
            Intent intent = new Intent(HomeActivity.this, FaceActivity.class);
            intent.putExtra("charge", charge);
            intent.putExtra("userid", userid);
            startActivity(intent);
        }

        @JavascriptInterface
        public void startgoPay(String url) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

        @JavascriptInterface
        public void clearData() {
            FileCacheUtils.cleanApplicationData(mContext, "com.hyp.pay");
        }


        @JavascriptInterface
        public void createVoice(String charge) {
            speak(charge);
        }

        @JavascriptInterface
        public void createPrintLog(String paymentid) {
//            获取姓名和交易凭证信息

            Log.d("olj","111111111111111111111111111111111111111111111111111111");
            Log.d("olj",paymentid);
            mPresenter.getUsr(SPUtil.getUserid());
            Log.d("olj","111111111111111111111111111111111111111111111111111111");
            Log.d("olj",paymentid);
            mPresenter.getFindRecharge(paymentid);



        }

        //        1清除cookie userid方法（h5调用）
        @JavascriptInterface
        public void closeExit() {
            SPUtil.removeAllcookies(SPUtil.getAllCookies());
            SPUtil.removeUserId(SPUtil.getUserid());
        }

        @JavascriptInterface
        public void startIdCard(int relaName) {
            if (relaName == 0) {
                Intent intent = new Intent(mContext, IDCardActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(mContext, AtteionActivity.class);
                startActivity(intent);
            }

        }

        @JavascriptInterface
        public void startPopWindow(String path) {
            mPop = new CustomPopupWindow(HomeActivity.this);
            mPop.setOnItemClickListener(HomeActivity.this);
            mPop.showAtLocation(HomeActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    }

    private void syncCookie2(Context context, String url) {

        try {
            String flag="";
            if (android.os.Build.DISPLAY.equals("NewLand_N900-7cfaf9357f")) {
                flag="1";
            }else{
                flag="0";
            }
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setCookie(url, "isPrintLog="+flag);
            CookieSyncManager.getInstance().sync();
//            String CookieStr = cookieManager.getCookie(url);
            String oldCookie = cookieManager.getCookie(url);
            if (oldCookie != null) {
                Log.d("olj_oldCookie", oldCookie);
            }

            SPUtil.setAllCookies(oldCookie);
            String a[] = oldCookie.split(";");
            Log.e("olj", a[2]);
            String b[] = a[2].split(",");
            Log.e("olj", b[0]);
            Log.e("olj", b[1]);
            Log.e("olj", b[2]);

            b[2] = b[2].trim();
            String str2 = "";
            if (b[2] != null && !"".equals(b[2])) {
                for (int i = 0; i < b[2].length(); i++) {
                    if (b[2].charAt(i) >= 48 && b[2].charAt(i) <= 57) {
                        str2 += b[2].charAt(i);
                    }
                }
            }
            SPUtil.setUserid(str2);
        } catch (Exception e) {
            Log.e("olj_failed", e.toString());
        }
    }


    private void initialEnv() {
        if (mSampleDirPath == null) {
            String sdcardPath = Environment.getExternalStorageDirectory().toString();
            mSampleDirPath = sdcardPath + "/" + SAMPLE_DIR_NAME;
        }
        makeDir(mSampleDirPath);
        copyFromAssetsToSdcard(false, SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_FEMALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_MALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, TEXT_MODEL_NAME, mSampleDirPath + "/" + TEXT_MODEL_NAME);
        copyFromAssetsToSdcard(false, LICENSE_FILE_NAME, mSampleDirPath + "/" + LICENSE_FILE_NAME);
        copyFromAssetsToSdcard(false, "english/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/"
                + ENGLISH_SPEECH_FEMALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, "english/" + ENGLISH_SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/"
                + ENGLISH_SPEECH_MALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, "english/" + ENGLISH_TEXT_MODEL_NAME, mSampleDirPath + "/"
                + ENGLISH_TEXT_MODEL_NAME);
    }

    private void makeDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 将sample工程需要的资源文件拷贝到SD卡中使用（授权文件为临时授权文件，请注册正式授权）
     *
     * @param isCover 是否覆盖已存在的目标文件
     * @param source
     * @param dest
     */
    private void copyFromAssetsToSdcard(boolean isCover, String source, String dest) {
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = getResources().getAssets().open(source);
                String path = dest;
                fos = new FileOutputStream(path);
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initialTts() {
        this.mSpeechSynthesizer = SpeechSynthesizer.getInstance();
        this.mSpeechSynthesizer.setContext(this);
        this.mSpeechSynthesizer.setSpeechSynthesizerListener(this);
        // 文本模型文件路径 (离线引擎使用)
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, mSampleDirPath + "/"
                + TEXT_MODEL_NAME);
        // 声学模型文件路径 (离线引擎使用)
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, mSampleDirPath + "/"
                + SPEECH_FEMALE_MODEL_NAME);
        // 本地授权文件路径,如未设置将使用默认路径.设置临时授权文件路径，LICENCE_FILE_NAME请替换成临时授权文件的实际路径，仅在使用临时license文件时需要进行设置，如果在[应用管理]中开通了正式离线授权，不需要设置该参数，建议将该行代码删除（离线引擎）
        // 如果合成结果出现临时授权文件将要到期的提示，说明使用了临时授权文件，请删除临时授权即可。
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_LICENCE_FILE, mSampleDirPath + "/"
                + LICENSE_FILE_NAME);
//        // 请替换为语音开发者平台上注册应用得到的App ID (离线授权)
//        this.mSpeechSynthesizer.setAppId("9751744"/*这里只是为了让Demo运行使用的APPID,请替换成自己的id。*/);
//        // 请替换为语音开发者平台注册应用得到的apikey和secretkey (在线授权)
//        this.mSpeechSynthesizer.setApiKey("Vq7tQk64Blvxx1ZfEyH25PtI",
//                "IfL68I092GYC3FGAgvtQisqERmZMGqXl"/*这里只是为了让Demo正常运行使用APIKey,请替换成自己的APIKey*/);

        // 请替换为语音开发者平台上注册应用得到的App ID (离线授权)
        this.mSpeechSynthesizer.setAppId("8535996"/*这里只是为了让Demo运行使用的APPID,请替换成自己的id。*/);
        // 请替换为语音开发者平台注册应用得到的apikey和secretkey (在线授权)
        this.mSpeechSynthesizer.setApiKey("MxPpf3nF5QX0pndKKhS7IXcB",
                "7226e84664474aa098296da5eb2aa434"/*这里只是为了让Demo正常运行使用APIKey,请替换成自己的APIKey*/);
        // 发音人（在线引擎），可用参数为0,1,2,3。。。（服务器端会动态增加，各值含义参考文档，以文档说明为准。0--普通女声，1--普通男声，2--特别男声，3--情感男声。。。）
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        // 设置Mix模式的合成策略
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);
        // 授权检测接口(只是通过AuthInfo进行检验授权是否成功。)
        // AuthInfo接口用于测试开发者是否成功申请了在线或者离线授权，如果测试授权成功了，可以删除AuthInfo部分的代码（该接口首次验证时比较耗时），不会影响正常使用（合成使用时SDK内部会自动验证授权）
        AuthInfo authInfo = this.mSpeechSynthesizer.auth(TtsMode.MIX);

        if (authInfo.isSuccess()) {
//            toPrint("auth success");
        } else {
            String errorMsg = authInfo.getTtsError().getDetailMessage();
//            toPrint("auth failed errorMsg=" + errorMsg);
        }

        // 初始化tts
        mSpeechSynthesizer.initTts(TtsMode.MIX);

    }


    private void speak(String charge) {

        int result = this.mSpeechSynthesizer.speak("您已收款" + charge + "元");

        if (result < 0) {
            toPrint("error,please look up error code in doc or URL:http://yuyin.baidu.com/docs/tts/122 ");
        }
    }


    /*
     * @param arg0
     */
    @Override
    public void onSynthesizeStart(String utteranceId) {
//        toPrint("onSynthesizeStart utteranceId=" + utteranceId);
    }

    /**
     * 合成数据和进度的回调接口，分多次回调
     *
     * @param utteranceId
     * @param data        合成的音频数据。该音频数据是采样率为16K，2字节精度，单声道的pcm数据。
     * @param progress    文本按字符划分的进度，比如:你好啊 进度是0-3
     */
    @Override
    public void onSynthesizeDataArrived(String utteranceId, byte[] data, int progress) {
        // toPrint("onSynthesizeDataArrived");
        mHandler.sendMessage(mHandler.obtainMessage(UI_CHANGE_SYNTHES_TEXT_SELECTION, progress, 0));
    }

    /**
     * 合成正常结束，每句合成正常结束都会回调，如果过程中出错，则回调onError，不再回调此接口
     *
     * @param utteranceId
     */
    @Override
    public void onSynthesizeFinish(String utteranceId) {
//        toPrint("onSynthesizeFinish utteranceId=" + utteranceId);
    }

    /**
     * 播放开始，每句播放开始都会回调
     *
     * @param utteranceId
     */
    @Override
    public void onSpeechStart(String utteranceId) {
//        toPrint("onSpeechStart utteranceId=" + utteranceId);
    }

    /**
     * 播放进度回调接口，分多次回调
     *
     * @param utteranceId
     * @param progress    文本按字符划分的进度，比如:你好啊 进度是0-3
     */
    @Override
    public void onSpeechProgressChanged(String utteranceId, int progress) {
        // toPrint("onSpeechProgressChanged");
        mHandler.sendMessage(mHandler.obtainMessage(UI_CHANGE_INPUT_TEXT_SELECTION, progress, 0));
    }

    /**
     * 播放正常结束，每句播放正常结束都会回调，如果过程中出错，则回调onError,不再回调此接口
     *
     * @param utteranceId
     */
    @Override
    public void onSpeechFinish(String utteranceId) {
//        toPrint("onSpeechFinish utteranceId=" + utteranceId);
    }

    /**
     * 当合成或者播放过程中出错时回调此接口
     *
     * @param utteranceId
     * @param error       包含错误码和错误信息
     */
    @Override
    public void onError(String utteranceId, SpeechError error) {
        toPrint("onError error=" + "(" + error.code + ")" + error.description + "--utteranceId=" + utteranceId);
    }

    private Handler mHandler = new Handler() {

        /*
         * @param msg
         */
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case PRINT:
                    print(msg);
                    break;
                case PHOTOS_SUCCESS:
                    mPop.dismiss();
                    break;
                default:
                    break;
            }
        }

    };

    private void toPrint(String str) {
        Message msg = Message.obtain();
        msg.obj = str;
        this.mHandler.sendMessage(msg);
    }

    private void print(Message msg) {
        String message = (String) msg.obj;
        if (message != null) {
            Log.w(TAG, message);
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }

}
